'''
Description: 
Author: Zilu
Date: 2021-11-15 20:09:42
Version: 
LastEditTime: 2021-11-15 21:31:04
LastEditors: Zilu
'''

# 所以，收取邮件分两步：
# 第一步：用poplib把邮件的原始文本下载到本地；
# 第二部：用email解析原始文本，还原为邮件对象。
from email import message
import poplib

email = input('Email:')
password = input('Password:')
pop3_server = input('POP3 server:')

server = poplib.POP3(pop3_server)
server.set_debuglevel(1)
# 可选：打印pop3服务器的欢迎文字
print(server.getwelcome().decode('utf-8'))

# 身份认证
server.user(email)
server.pass_(password)

# stat 返回邮件数量和占有空间
print('Message: %s. Size: %s' % server.stat())
# list() 返回所有邮件的编号
resp, mails, octets = server.list()
# 可以查看返回的列表类似[b'1 82923', b'2 2184', ...]
print(mails)

# 获取最新的一封邮件，索引号从1开始
index = len(mails)
resp, lines, octets = server.retr(index)

# lines获取了最新一封邮件的每一行
msg_content = b'\r\n'.join(lines).decode('utf-8')
# 解析出邮件
from email.parser import Parser
msg = Parser().parsestr(msg_content)

# 可以直接删除文件
# server.dele(index)
server.quit()

from email.parser import Parser
from email.header import decode_header
from email.utils import parseaddr
from email.message import Message

# 值得看看
# indent用于缩进显示:
def print_info(msg:Message, indent=0):
    if indent == 0:
        for header in ['From', 'To', 'Subject']:
            value = msg.get(header, '')
            if value:
                if header=='Subject':
                    value = decode_str(value)
                else:
                    hdr, addr = parseaddr(value)
                    name = decode_str(hdr)
                    value = u'%s <%s>' % (name, addr)
            print('%s%s: %s' % ('  ' * indent, header, value))
    if (msg.is_multipart()):
        parts = msg.get_payload()
        for n, part in enumerate(parts):
            print('%spart %s' % ('  ' * indent, n))
            print('%s--------------------' % ('  ' * indent))
            print_info(part, indent + 1)
    else:
        content_type = msg.get_content_type()
        if content_type=='text/plain' or content_type=='text/html':
            content = msg.get_payload(decode=True)
            charset = guess_charset(msg)
            if charset:
                content = content.decode(charset)
            print('%sText: %s' % ('  ' * indent, content + '...'))
        else:
            print('%sAttachment: %s' % ('  ' * indent, content_type))

# 邮件的Subject或者Email中包含的名字都是经过编码后的str，要正常显示，就必须decode
def decode_str(s):
    value, charset = decode_header(s)[0]
    if charset:
        value = value.decode(charset)
    return value

# 文本邮件的内容也是str，还需要检测编码，否则，非UTF-8编码的邮件都无法正常显示
def guess_charset(msg):
    charset = msg.get_charset()
    if charset is None:
        content_type = msg.get('Content-Type', '').lower()
        pos = content_type.find('charset=')
        if pos >= 0:
            charset = content_type[pos + 8:].strip()
    return charset

print_info(msg)



